<?php
class Admin_UserController extends Apps_Controller_Action {
// Default UserId
	const DEFAULT_USER_ID = 1;

	public function indexAction() {
		$this->_redirect('/admin/user/read/');
	}
	/*
	 * Show list user
	 */
	public function readAction() {
		$q = $this->_dbAdapter
				  ->select()
				  ->from('user', null)
				  ->join('user_group', 'user_group.id = user.user_group_id', null)
				  ->where('user.id != ?', self::DEFAULT_USER_ID)
				  ->columns(array(
				      'id' 				=> 'user.id',
				  	  'username' 		=> 'user.username',
				  	  'full_name' 		=> 'user.full_name',
				  	  'group_name' 		=> 'user_group.name',
				  	  'phone'			=> 'user.phone',
				  	  'email'			=> 'user.email',
				  	  'address'			=> 'user.address',
				  	  'description' 	=> 'user.description',
					  'created_date' 	=> 'user.created_date'
				  ));

		$grid = new Grid_User_User('user-grid');
		$grid->setSource(new OeZend_Widget_Grid_Source_ZendDbSelect($q))
		     ->setCaption('User List')
		     ->setDisableCheckbox()
		     ->setDisablePaginator()
		     ->setView(new OeZend_Widget_Grid_View())
		     ->deploy();

		$this->view->grid = $grid;
	}

	public function createAction() {
		$rq   = $this->_request;
        $form = new Admin_Form_UserAdd();
        if($rq->isPost()) {
            if($form->isValid($rq->getParams())) {
        	    $tbUser = new Model_DbTable_User();

            	$d = $form->getValues();
            	$d['password'] = md5($d['password']);

            	unset($d['passwordConfirm']);

            	$r = $tbUser->safelyInsert($d);
                $this->_flashMessenger->addMessage(
                	$r
                    ? self::$msgAddSuccess
                    : self::$msgAddFailed);
                return $this->goToActionIndex();
            }
        }

        $this->view->form = $form;
	}

	public function updateAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');
        $form = new Admin_Form_UserEdit();
        $tbUser = new Model_DbTable_User();

		if(!$id || !($r = $tbUser->fetchRow(array('id=?' => $id))->toArray())) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            return $this->goToActionIndex();
        }

        // User default cannot edit
	        if($id == self::DEFAULT_USER_ID) {
	        	$this->_flashMessenger->addMessage('Người dùng mặc định không được thay đổi');
	        	return $this->goToActionIndex();
	        }

        if($rq->isPost()) {
            if($form->isValid($rq->getParams())) {
            	$d = $form->getValues();
            	$d['password'] = md5($d['password']);
            	unset($d['passwordConfirm']);
            	$r = $tbUser->safelyUpdate($d, array('id = ?' => $id));
                $this->_flashMessenger->addMessage(
                    $r
                    ? self::$msgUpdateSuccess
                    : self::$msgUpdateFailed);
                return $this->goToActionIndex();
            }
        } else {
            $form->populate($r);
        }
		$form->setLegend('Edit User');
        $this->view->form = $form;
        $this->render('create');
	}

	public function deleteAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$userIds = $rq->getParam('id');
		if(!$userIds) {
			$this->goToActionIndex();
		}
		$tbUser   = new Model_DbTable_User();
		if(is_array($userIds)) {
			foreach ($userIds as $userId) {

				// User_Default cannot delete
					if($userId == self::DEFAULT_USER_ID) {
						$this->_flashMessenger->addMessage('Người dùng quản trị. Không được xóa');
						return $this->goToActionIndex();
					}

				$r = $tbUser->safelyDelete(array('id = ?' => $userId));
			}
			$this->goToActionIndex();
		} elseif (is_numeric($userIds)) {

			// User_Default cannot delete
				if($userIds == self::DEFAULT_USER_ID) {
					$this->_flashMessenger->addMessage('Người dùng quản trị. Không được xóa');
					return $this->goToActionIndex();
				}
			$r = $tbUser->safelyDelete(array('id = ?' => $userIds));
			$this->_flashMessenger->addMessage($r ? self::$msgDeleteSuccess : self::$msgDeleteError);
			$this->goToActionIndex();
		} else {
			$this->goToActionIndex();
		}
	}

}
